import { useEffect, useRef } from 'react';
import { init, graphic } from 'echarts';

export default function BatteryBar() {
  const domRef = useRef(null);

  const initChart = () => {

    const chart = init(domRef.current, 'purple');
    chart.setOption({
      graphic: [
        {
          type: 'rect',
          shape: {
            x: 50,
            y: 50,
            width: 220,
            height: 100,
            r: 8,
          },
          style: {
            fill: 'rgba(0, 0, 0, 0)',
            stroke: '#000',
            lineWidth: 6
          }
        },
        {
          type: 'rect',
          shape: {
            x: 270,
            y: 75,
            width: 10,
            height: 50,
            r: [0, 4, 4, 0],
          },
          style: {
            fill: '#000',
            stroke: '#000',
            lineWidth: 2
          }
        },
        {
          id: 'battery-level',
          type: 'rect',
          shape: {
            x: 55,
            y: 55,
            width: 0,
            height: 90,
            r: 4,
          },
          style: {
            fill: '#4caf50'
          }
        }
      ],
      xAxis: {
        show: false
      },
      yAxis: {
        show: false
      },
      series: [
        {
          type: 'custom',
          renderItem: function (params, api) {
            const value = api.value(0);
            const batteryWidth = (210 * value) / 100;
            const color = value < 10 ? '#f44336' : '#4caf50';
            return  {
              type: 'rect',
              shape: {
                x: 55,
                y: 55,
                width: batteryWidth,
                height: 90,
                r: 4
              },
              style: {
                fill: color
              }
            };
          },
          data: [100] // Data to control the value
        }
      ]
    });
  }


  useEffect(() => {
    initChart();
  }, [])
  return (
    <div ref={domRef} className='battery-chart'></div>
  );
}
